﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace JLM2
{
    public partial class Setting : Form
    {
        protected JLMComm comm = null;
        protected JLMPLCCommands jlcCommands = null;
        /// <summary>
        /// lrc算法函数
        /// </summary>
        /// <param name="data">byte数组</param>
        /// <returns>计算出的lrc值</returns>
        private byte CalcLRC(byte[] data)
        {
            byte lrc = 0;
            for (int i = 0; i < data.Length; i++)
            {
                lrc += data[i];
            }
            lrc %= 255;
            lrc = (byte)~lrc;
            lrc += 1;
            return lrc;
        }

        private byte[] HexStringToHexBuffer(string hexString)
        {
            //string testCmd2 = "01 03 06 14 00 08";
            string[] chars = hexString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            byte[] returnBytes = new byte[chars.Length];
            for (int i = 0; i < chars.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(chars[i], 16);
            }
            return returnBytes;
        }

        public Setting()
        {
            InitializeComponent();
            timer1.Interval = 1200;
            timer1.Start();

            if (File.Exists(@"jlm_Interval.config"))
            {
                JLMConfig jlm_Interval = new JLMConfig(@"jlm_Interval.config");
                txt_ReadingInterval.Text = jlm_Interval.ConfigParam;
            }
            else txt_ReadingInterval.Text = "1";
        }

        public void SetParam(JLMComm c, JLMPLCCommands commands)
        {
            comm = c;
            jlcCommands = commands;
        }

        private void Setting_Load(object sender, EventArgs e)
        {
            comboSerialPort1.Items.Clear();

            foreach (string com in SerialPort.GetPortNames())
            {
                comboSerialPort1.Items.Add(com);
            }
            comboSerialPort1.DropDownStyle = ComboBoxStyle.DropDownList;

            if (comboSerialPort1.Items.Count > 0)
            {
                comboSerialPort1.SelectedIndex = 0;
            }
        }

        private void btn_SavePortConfig_Click(object sender, EventArgs e)
        {
            string Port1 = comboSerialPort1.Text;
            if (string.IsNullOrEmpty(Port1))
            {
                MessageBox.Show($"至少保存一个端口!", "提示");
                return;
            }

            int Reading_Interval;
            if (string.IsNullOrEmpty(txt_ReadingInterval.Text) || !int.TryParse(txt_ReadingInterval.Text, out Reading_Interval))
            {
                MessageBox.Show($"读取间隔必须为数字!", "提示");
                return;
            }

            if (File.Exists(@"jlm.config"))
                File.Delete(@"jlm.config");
            FileStream configFile = new FileStream(@"jlm.config", FileMode.Create);

            if (File.Exists(@"jlm_Interval.config"))
                File.Delete(@"jlm_Interval.config");
            FileStream config_IntervalFile = new FileStream(@"jlm_Interval.config", FileMode.Create);

            //开始写入
            byte[] buffer = Encoding.ASCII.GetBytes(Port1);
            configFile.Write(buffer, 0, buffer.Length);
            configFile.Flush();
            configFile.Close();

            byte[] buffer1 = Encoding.ASCII.GetBytes(txt_ReadingInterval.Text);
            config_IntervalFile.Write(buffer1, 0, buffer1.Length);
            config_IntervalFile.Flush();
            config_IntervalFile.Close();

            MessageBox.Show("配置已保存，重新启动程序生效！");
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            JLMSystemSetParam Param = new JLMSystemSetParam();
            comm.ReadXTCSSZParam(Param);
            textGLWJ.Text = Param.GLWJ;
            textBXBL.Text = Param.BXBL;
            textGYBKS.Text = Param.GYBKS;
            textDQYL.Text = Param.DQYL;
            textZATGS.Text = Param.ZATGS;
            textDQWD.Text = Param.DQWD;
            textPCWD.Text = Param.PCWD;

            textWWD1.Text = Param.DQWWD;
            textWWDPC1.Text = Param.WWDPC;
            textNWD2.Text = Param.NWD;
            textNWDPC2.Text = Param.NWDPC;
            textWWD3.Text = Param.DQWWD3;
            textWWDPC3.Text = Param.WWDPC3;
            textNWD4.Text = Param.NWD4;
            textNWDPC4.Text = Param.NWDPC4;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            JLMSystemSetParam Param = new JLMSystemSetParam();
            Param.GLWJ = textGLWJ.Text;
            Param.BXBL = textBXBL.Text;
            Param.GYBKS = textGYBKS.Text;
            Param.DQYL = textDQYL.Text;
            Param.ZATGS = textZATGS.Text;

            Param.DQWWD = textWWD1.Text;
            Param.WWDPC = textWWDPC1.Text;
            Param.NWD = textNWD2.Text;
            Param.NWDPC = textNWDPC2.Text;
            Param.DQWWD3 = textWWD3.Text;
            Param.WWDPC3 = textWWDPC3.Text;
            Param.NWD4 = textNWD4.Text;
            Param.NWDPC4 = textNWDPC4.Text;

            comm.WriteXTCSSZParam(Param);
            //MessageBox.Show("参数已保存！");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            comm.ControlBtn(jlcCommands.xtcsBTNQP, true);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            comm.ControlBtn(jlcCommands.xtcsBTNJZ, true);
        }

        private void btn_Pos1Refresh_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            JLMTSYMParam param = new JLMTSYMParam();
            comm.ReadTSYMParam(param);
            textSD.Text = param.SD;
            textCurrentYL1.Text = param.DQYL1;
            textCurrentYL2.Text = param.DQYL2;
            textCurrentYL3.Text = param.DQYL3;
            textCurrentYL4.Text = param.DQYL4;

            textSZYL1.Text = param.SZYL1;
            textSZYL2.Text = param.SZYL2;
            textSZYL3.Text = param.SZYL3;
            textSZYL4.Text = param.SZYL4;

            textMNLSC.Text = param.MNLSC;
            textMNLDS.Text = param.MNLDS;
            timer1.Start();
        }

        private void btn_BPQ_FJ_Click(object sender, EventArgs e)
        {

        }

        private void btn_BPQ_ZJ_Click(object sender, EventArgs e)
        {
        }

        private void button7_Click(object sender, EventArgs e)
        {

        }

        bool YYQGJDQ = false;
        private void button8_Click(object sender, EventArgs e)
        {
            string cmd = "01 05 08 98";
            if (YYQGJDQ)
            {
                comm.ControlBtn(cmd, false);
                button8.BackColor = Color.LightGray;
                YYQGJDQ = false;
            }
            else
            {
                comm.ControlBtn(cmd, true);
                button8.BackColor = Color.LightGreen;
                YYQGJDQ = true;
            }
        }

        bool YYDJDQ = false;
        private void button6_Click(object sender, EventArgs e)
        {
            string cmd = "01 05 08 97";
            if (YYDJDQ)
            {
                button6.BackColor = Color.LightGray;
                comm.ControlBtn(cmd, false);
                YYDJDQ = false;
            }
            else
            {
                comm.ControlBtn(cmd, true);
                button6.BackColor = Color.LightGreen;
                YYDJDQ = true;
            }
        }

        bool YYQGHTJDQ = false;
        private void button9_Click(object sender, EventArgs e)
        {
            string cmd = "01 05 08 99";
            if (YYQGHTJDQ)
            {
                button9.BackColor = Color.LightGray;
                comm.ControlBtn(cmd, false);
                YYQGHTJDQ = false;
            }
            else
            {
                comm.ControlBtn(cmd, true);
                button9.BackColor = Color.LightGreen;
                YYQGHTJDQ = true;
            }
        }

        private void button10_MouseDown(object sender, MouseEventArgs e)
        {
            string cmd = "01 05 08 00";
            comm.ControlBtn(cmd, true);
        }

        private void button10_MouseUp(object sender, MouseEventArgs e)
        {
            string cmd = "01 05 08 00";
            comm.ControlBtn(cmd, false);
        }

        private void button11_MouseDown(object sender, MouseEventArgs e)
        {
            string cmd = "01 05 08 01";
            comm.ControlBtn(cmd, true);
        }

        private void button11_MouseUp(object sender, MouseEventArgs e)
        {
            string cmd = "01 05 08 01";
            comm.ControlBtn(cmd, false);
        }

        private void btn_Pos1Setting_Click(object sender, EventArgs e)
        {
            try
            {
                timer1.Stop();
                if (!string.IsNullOrEmpty(textSZYL1.Text))
                {
                    string yl = textSZYL1.Text;
                    string y1_Address = "12 18"; // D536=12 18
                    comm.Write32BitParam(yl, y1_Address);
                }

                if (!string.IsNullOrEmpty(textSZYL2.Text))
                {
                    string y2 = textSZYL2.Text;
                    string y2_Address = "11 ae"; // D430=11 ae
                    comm.Write32BitParam(y2, y2_Address);
                }

                if (!string.IsNullOrEmpty(textSZYL3.Text))
                {
                    string y3 = textSZYL3.Text;
                    string y3_Address = "11 b0"; // D432=11 b0
                    comm.Write32BitParam(y3, y3_Address);
                }

                if (!string.IsNullOrEmpty(textSZYL4.Text))
                {
                    string y4 = textSZYL4.Text;
                    string y4_Address = "11 b2"; // D434=11 b2 
                    comm.Write32BitParam(y4, y4_Address);
                }
                timer1.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            JLMTSYMParam param = new JLMTSYMParam();
            comm.ReadTSYMParam(param);
            textCurrentYL1.Text = param.DQYL1;
            textCurrentYL2.Text = param.DQYL2;
            textCurrentYL3.Text = param.DQYL3;
            textCurrentYL4.Text = param.DQYL4;
        }

        private void Setting_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer1.Stop();
        }

        private void Btn_RatioParamsRead_Click(object sender, EventArgs e)
        {
            Thread myThread = new Thread(running =>
            {
                JLMBLSetParam param = new JLMBLSetParam();
                comm.ReadBLCSSZParam(param);
                this.Invoke(new Action(() =>
                {
                    textYL1.Text = param.BL1;
                    textYL2.Text = param.BL2;
                    textYL3.Text = param.BL3;
                    textYL4.Text = param.BL4;
                    textYL5.Text = param.BL5;
                    textYL6.Text = param.BL6;
                    textYL7.Text = param.BL7;
                    textYL8.Text = param.BL8;
                    textYL9.Text = param.BL9;
                    textYL10.Text = param.BL10;
                }));
            });
            myThread.IsBackground = false;
            myThread.Start();
        }

        private void Btn_RatioParamsWrite_Click(object sender, EventArgs e)
        {
            JLMBLSetParam param = new JLMBLSetParam();
            param.BL1 = textYL1.Text;
            param.BL2 = textYL2.Text;
            param.BL3 = textYL3.Text;
            param.BL4 = textYL4.Text;
            param.BL5 = textYL5.Text;
            param.BL6 = textYL6.Text;
            param.BL7 = textYL7.Text;
            param.BL8 = textYL8.Text;
            param.BL9 = textYL9.Text;
            param.BL10 = textYL10.Text;
            comm.WriteBLCSSZParam(param);
            //MessageBox.Show("参数已设置！");
        }
    }
}